package com.ctu.app.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.log4j.Logger;

import com.ctu.autodial.CrashApplication;
import com.ctu.autodial.MainActivity;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created with IntelliJ IDEA. User: kaiz Date: 13-8-28 Time: 下午4:55 To change
 * this template use File | Settings | File Templates.
 */
public class Request {
	private static final String TAG = "Request";
	private static final String EXCEPTION_FILE_NAME = "AutoDialRunException";
	private static Logger runLogger;
	// URL destination;
	// BufferedOutputStream os = null;
	// HttpURLConnection connection = null;
	// private static final String USERAGENT =
	// "CTU_Phone_Test_1.0.0;android/receipts";

	String url = null;
	byte[] data = null;
	Response ret = null;
	Thread thread = null;
	Activity activity = null;
	final int MAX_RETRY_COUNT = 6;
	final int RETRY_INTERVAL = 1500;

	public Request(Activity caller) {

		activity = caller;
		runLogger = CrashApplication.getLoggerInstance();
	}

	public void Send(String aUrl, byte[] aData, Response aRet) {
		this.url = aUrl;
		this.data = aData;
		this.ret = aRet;
		this.thread = new Thread(runnable);
		thread.start();
	}

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// ByteArrayEntity arrayEntity = new ByteArrayEntity(data);
			// arrayEntity.setContentType("application/octet-stream");

			tryConnect();// 尝试连接网络 每个1.5s重连一次

			// HttpPost httpPost = new HttpPost(url);
			// httpPost.setEntity(arrayEntity);

			Log.d(TAG, "request---->" + url);
			HttpGet httpGet = new HttpGet(url);
			DefaultHttpClient client = new DefaultHttpClient();

			try {
				client.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 1000);
				client.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, 10 * 1000);

				HttpResponse response = client.execute(httpGet);
				// HttpResponse response = client.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
					Log.i(TAG, "连接成功!!!!");
					BufferedHttpEntity retEntity = new BufferedHttpEntity(
							response.getEntity());
					final InputStream is = retEntity.getContent();

					Log.d(TAG, "activity---->" + activity);

					activity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Log.d(TAG, "ret---->" + ret);
							ret.Ret(HttpURLConnection.HTTP_OK, is);// 返回连接状态和输入流
						}
					});

				} else {
					Log.e("kaiz", "Connection Failed: "
							+ response.getStatusLine().getStatusCode());
					final int errorCode = response.getStatusLine()
							.getStatusCode();
					activity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// DisplayError("网络连接错误，请稍后再试");
							Log.e("kaiz", "network error: " + errorCode);
							ret.Ret(errorCode, null);
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
				final String msg = e.getMessage();
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Log.e("kaiz", "connection error: " + msg);// DisplayError("连接云端失败，请稍后再试");
						ret.Ret(-2, null);
					}
				});
			}
		}

	};

	/**
	 * 尝试连接网络 每个1.5s重连一次
	 */
	private void tryConnect() {
		int retryCount = 0;
		try {

			while (!isConnected() && retryCount < MAX_RETRY_COUNT) {
				retryCount++;
				Log.d("kaiz", "retryCount++");
				thread.sleep(RETRY_INTERVAL);
			}

			if (retryCount >= MAX_RETRY_COUNT) {
				// DisplayError("没有检查到可用的网络，请设置后再试");
				ret.Ret(-1, null);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断wifi和移动的网络状态
	 * 
	 * @return
	 */
	boolean isConnected() {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) activity
				.getSystemService(activity.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			if (mNetworkInfo.isAvailable()) {
				NetworkInfo.State gprs = mConnectivityManager.getNetworkInfo(
						ConnectivityManager.TYPE_MOBILE).getState();
				NetworkInfo.State wifi = mConnectivityManager.getNetworkInfo(
						ConnectivityManager.TYPE_WIFI).getState();
				if (gprs == NetworkInfo.State.CONNECTED
						|| gprs == NetworkInfo.State.CONNECTING) {
					return true;
				}
				if (wifi == NetworkInfo.State.CONNECTED
						|| wifi == NetworkInfo.State.CONNECTING) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 流转换成String
	 * 
	 * @param is
	 * @return
	 */
	public static String inputStream2String(InputStream is) {
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		try {
			while ((line = in.readLine()) != null) {
				buffer.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();

			// LogUtil.saveExceptionLog2File(e, EXCEPTION_FILE_NAME);
			runLogger.error(e);
		}
		return buffer.toString();
	}
}
